<template>
    <div>
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="入库单编号">
                        <el-input placeholder="请输入编号" v-model="params.recptCode" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="7">
                    <el-form-item label="入库单名称">
                        <el-input placeholder="请输入名称" v-model="params.recptName" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="供应商名称">
                        <el-input placeholder="请输入名称" v-model="params.supplierName" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="12">
                <el-col :span="6">
                    <el-form-item label="订单编号">
                        <el-input v-model="params.poCode" placeholder="请输入编号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库日期">
                        <el-date-picker v-model="params.recptDate" align="right" type="date" placeholder="选择日期"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
            </el-row>

            <el-button style="background-color:#ADD8E6" @click="insert" :icon="Plus">新增</el-button>
            <el-button style=" background-color: #90EE90" :icon="Edit" :disabled="isSingleRowSelected"
                @click="updateID">修改</el-button>
            <el-button style="background-color: #FFCCCB" @click="Delete1" plain :disabled="deleteDisabled"
                :icon="Delete">删除</el-button>

            <div style="display: flex; flex-direction: column; gap: 10px;">
                <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column prop="recptCode" label="入库单编码" width="150"></el-table-column>
                    <el-table-column prop="recptName" label="入库单名称" width="150"></el-table-column>
                    <el-table-column prop="supplierName" label="供应商名称" width="150"></el-table-column>
                    <el-table-column prop="recptDate" label="入库日期" width="250"></el-table-column>
                    <el-table-column prop="poCode" label="采购订单号" width="150"></el-table-column>
                    <el-table-column prop="totalAmount" label="单价" width="150"></el-table-column>
                    <el-table-column prop="status" label="单据状态" width="150">
                        <template #default="scope">
                            {{ scope.row.status === '0' ? '草稿' : '已完成' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="300">
                        <template #default="scope">
                            <!-- 只有在状态为草稿时显示修改和删除按钮 -->
                            <div v-if="scope.row.status === '0'">
                                <el-button link type="primary" @click="rk(scope.row)" :icon="Edit">执行入库</el-button>
                                <el-button link type="primary" @click="update(scope.row)" :icon="Edit">修改</el-button>
                                <el-button type="primary" link @click="Delete2(scope.row)" :icon="Delete">删除</el-button>
                            </div>
                            <!-- 当状态为已完成时，不显示任何按钮 -->
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-row>
                <el-col :span="24">
                    <div class="demo-pagination-block">
                        <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                            :page-sizes="pageSizes" layout="total, sizes, prev, pager, next, jumper"
                            :total="pageResult.total" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
        </el-form>




        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="60%" @close="handleClose">
            <el-form ref="form" :model="formdata" label-width="100px">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="入库单编号">
                            <el-input v-model="formdata.recptCode" placeholder="请输入编号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库单名称">
                            <el-input v-model="formdata.recptName" placeholder="请输入名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="入库日期">
                            <el-date-picker v-model="formdata.recptDate" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="采购订单号">
                            <el-input v-model="formdata.poCode" placeholder="请输入订单号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商">
                            <el-input v-model="formdata.supplierName" style="max-width: 600px" placeholder="请选择供应商"
                                readonly>
                                <template #append>
                                    <el-button :icon="Search" @click="customerSelect" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="选择仓库">
                            <el-cascader v-model="formdata.warehouseNames" ref="cascader" :options="options"
                                @change="handleChange" placeholder="请选择仓库" clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单据状态">
                            <el-select v-model="formdata.status" disabled>
                                <el-option value="0" label="草稿"> </el-option>
                                <el-option value="1" label="已完成"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="总金额">
                            <el-input v-model="formdata.totalAmount" placeholder="" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="formdata.remark" placeholder="请输入备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!--物料部分-->
                <el-tabs type="border-card" v-show="activeName">
                    <el-tab-pane label="物料信息">
                        <el-button style="background-color:#ADD8E6" @click="Wlinsert">新增</el-button>
                        <el-button style="background-color: #FFCCCB" plain :disabled="deleteDisabled"
                            @click="Deletewl1">删除</el-button>
                        <el-table style="width: 100%" :data="formdata.line"
                            @selection-change="handleSelectionChangebom">
                            <el-table-column type="selection" width="50"></el-table-column>
                            <el-table-column prop="materialProductCode" label="物料编码" width="100"></el-table-column>
                            <el-table-column prop="productName" label="物料名称" width="100"></el-table-column>
                            <el-table-column prop="specificationAndModel" label="规格型号" width="100"></el-table-column>
                            <el-table-column prop="wocumentAmount" label="单据金额" width="100"></el-table-column>
                            <el-table-column prop="unitName" label="单位" width="100"></el-table-column>
                            <el-table-column prop="quantityReceived" label="入库数量" width="100"></el-table-column>
                            <el-table-column prop="batchCode" label="批次号" width="100"></el-table-column>
                            <el-table-column prop="warehouseName" label="仓库" width="100"></el-table-column>
                            <el-table-column prop="warehouseAreaName" label="库区" width="100"></el-table-column>
                            <el-table-column prop="warehouseLocationName" label="库位" width="100"></el-table-column>
                            <el-table-column prop="expireDate" label="有效期" width="200"></el-table-column>
                            <el-table-column prop="remark" label="备注" width="100"></el-table-column>
                            <el-table-column label="操作" width="200px">
                                <template #default="scope">
                                    <el-button :row="scope.row" link type="primary" @click="Wlupdate(scope.row)"
                                        :icon="Edit">修改</el-button>
                                    <el-button type="primary" link @click="Deletewl2(scope.row)"
                                        :icon="Delete">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <!-- 分页组件 -->
                    <el-row>
                        <el-col :span="24">
                            <div class="demo-pagination-block">
                                <el-pagination v-model:current-page="paramsline.currentPage"
                                    v-model:page-size="paramsline.pageSize" background
                                    :default-page-size="paramsline.pageSize" :page-sizes="pageSizesline"
                                    layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResultline.total)"
                                    @size-change="handleSizeChangeline" @current-change="handleCurrentChangeline">
                                </el-pagination>
                            </div>
                        </el-col>
                    </el-row>
                    <!-- 分页组件结束 -->
                </el-tabs>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                    <el-button @click="close">关闭</el-button>
                </div>
            </template>
        </el-dialog>




        <el-dialog :destroy-on-close="true" :gystitle="gystitle" v-model="customerVisible" width="70%">
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <el-table style="width: 100%" :data="ghssalesorder" @row-click="handleRowClick">
                    <el-table-column prop="supplierCode" label="供应商编码" width="150"></el-table-column>
                    <el-table-column prop="supplierName" label="供应商名称" width="150"></el-table-column>
                    <el-table-column prop="supplierAbbreviation" label="供应商简称" width="150"></el-table-column>
                    <el-table-column prop="supplierGrade" label="供应商等级" width="150" v-slot="scope">
                        <el-tag :type="scope.row.supplierGrade == '0' ? 'warning' : 'info'">
                            {{ scope.row.supplierGrade == '0' ? 'A级' : 'B级' }}
                        </el-tag>
                    </el-table-column>
                    <el-table-column prop="supplierScore" label="供应商评分" width="150"></el-table-column>
                    <el-table-column prop="supplierPhone" label="供应商电话" width="150"></el-table-column>
                    <el-table-column prop="status" label="是否启用" width="180" v-slot="scope">
                        <el-tag :type="scope.row.status == '0' ? 'success' : 'danger'">
                            {{ scope.row.status == '0' ? '是' : '否' }}
                        </el-tag>
                    </el-table-column>
                </el-table>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmitghs">确定</el-button>
                    <el-button type="primary" @click="closegys">关闭</el-button>
                </div>
            </template>
        </el-dialog>


        <el-dialog :destroy-on-close="true" :title="wltitle" v-model="WlVisible" width="50%" @close="handleClose_wl">
            <el-form ref="form" :model="wlformdata" label-width="100px">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="物料编号">
                            <el-input v-model="wlformdata.materialProductCode" style="max-width: 600px" readonly>
                                <template #append>
                                    <el-button :icon="Search" @click="wlSelect" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="物料名称">
                            <el-input v-model="wlformdata.productName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="入库数量">
                            <el-input-number v-model="wlformdata.quantityReceived" @change="handleChange" :min="0"
                                :max="2000" label="入库数量"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单据金额">
                            <el-input-number v-model="wlformdata.wocumentAmount" @change="handleChange" :min="0"
                                :max="2000" label="单据金额"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位">
                            <el-input v-model="wlformdata.unitName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="选择仓库">
                            <el-cascader v-model="wlformdata.warehouseNames" ref="cascader" :options="options"
                                @change="handleChange" placeholder="请选择仓库" clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库批次号">
                            <el-input v-model="wlformdata.batchCode" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="有效期">
                            <el-date-picker v-model="wlformdata.expireDate" type="date"
                                placeholder="选择日期"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="wlformdata.remark" placeholder="请输入备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <template v-slot:footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="WlOnSubmit">确定</el-button>
                    <el-button @click="wlclose">关闭</el-button>
                </div>
            </template>
        </el-dialog>



        <el-dialog :destroy-on-close="true" :title="titlebom" v-model="visibleBom" width="70%">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-table style="width: 100%" :data="wlsalesorder" @selection-change=""
                        @row-click="handleRowClickwl">
                        <el-table-column prop="materialProductCode" label="物料编码" width="120"></el-table-column>
                        <el-table-column prop="productName" label="物料名称" width="120"></el-table-column>
                        <el-table-column prop="specificationAndModel" label="规格型号" width="120"></el-table-column>
                        <el-table-column prop="unitName" label="单位" width="120"></el-table-column>
                        <el-table-column prop="material" label="物料/产品" width="120" v-slot="options">
                            <span v-if="options.row.material == 0">物料</span>
                            <span v-if="options.row.material == 1">产品</span>
                        </el-table-column>
                        <el-table-column prop="materialName" label="所属分类" width="120">
                            <template #default="scope">
                                {{ scope.row.materialName }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="是否启用" width="150" v-slot="options">
                            <span v-if="options.row.status == '0'">是</span>
                            <span v-if="options.row.status == '1'">否</span>
                        </el-table-column>
                        <el-table-column prop="setSafetyStock" label="设置安全库存" width="150" v-slot="options">
                            <span v-if="options.row.setSafetyStock == '0'">是</span>
                            <span v-if="options.row.setSafetyStock == '1'">否</span>
                        </el-table-column>
                        <el-table-column prop="creationTime" label="创建时间" width="200"></el-table-column>
                    </el-table>
                </el-col>
            </el-row>

            <!-- 将按钮移到 el-row 外面 -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit_wl">确定</el-button>
                    <el-button type="primary" @click="close_wl">关闭</el-button>
                </div>
            </template>
        </el-dialog>

    </div>






</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import {
    findrkd, insertrkd, updaterkd, findWarehousesList, findSupplier, deleterkd,
    findline, insertline, updateline, deleteline, findmaterialManagement, insertStock
} from '@/apis/xms';
import { Search, Refresh, Delete, Plus, EditPen, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';


const activeName = ref(false) // 弹窗tab页
const ids = ref([]); // 选中行的id数组
const idswl = ref([]); // 选中物料行的id数组
const deleteDisabled = ref(true); // 删除按钮禁用状态
const pageResult = ref({}); // 初始值包含 total 属性
const titlebom = ref(""); // 选则物料弹窗标题
const visibleBom = ref(false); //选择物料弹窗状态


let salesorder = ref([]); // 表格数据
let ghssalesorder = ref([]); // 供应商列表数据
let wlsalesorder = ref([]); // 物料列表数据
const title = ref(""); // 弹窗标题
const visible = ref(false); // 弹窗状态
const options = ref([]); // 仓库列表
const customerVisible = ref(false); // 供应商弹窗状态
const WlVisible = ref(false); //物料新增弹窗
const wltitle = ref(""); // 物料新增弹窗标题
const gystitle = ref(""); // 供应商弹窗标题


const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
let roleVal = ref([]); //选中行

const formdata = ref({
    recptCode: "",
    recptName: "",
    recptDate: "",
    poCode: "",
    supplierName: "",
    warehouseCode: "",
    warehouseNames: [],
    status: '0',
    totalAmount: "",
    remark: "",
    line: [],
});


const wlformdata = ref({
    materialProductCode: "",
    productName: "",
    quantityReceived: 0,
    wocumentAmount: 0,
    unitId: "",
    unitName: "",
    warehouseNames: [],
    batchCode: "",
    expireDate: "",
    remark: "",

});

const pageSizesline = [2, 5, 8, 10] //  分页大小  
const pageResultline = ref({ total: 0 }) // 分页数据


// 分页大小
const pageSizes = [2, 5, 8, 10];

const params = ref({
    currentPage: 1,
    pageSize: 5,
    recptCode: "",
    recptName: "",
    supplierName: "",
    recptDate: "",
    poCode: "",
});



const paramsline = ref({
    currentPage: 1,
    pageSize: 5,
    recptCode: '',
});




// 搜索条件
const handleSearch = async () => {
    pageResult.value = await findrkd(params.value)
    salesorder.value = pageResult.value.records
}
//处理分页大小
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await findrkd(params.value)
    salesorder.value = pageResult.value.records
}

//处理当前分页数据
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await findrkd(params.value)
    salesorder.value = pageResult.value.records
}



const handleSearchline = async () => {
    console.log(paramsline.value);
    pageResultline.value = await findline(paramsline.value);
    console.log('数据', pageResultline.value);
    //更新本地数据
    formdata.value.line = pageResultline.value.records[0].line;

};

const handleCurrentChangeline = async (currentPage) => {
    paramsline.value.currentPage = currentPage;
    await handleSearchline(); // 数据刷新
};

const handleSizeChangeline = async (size) => {
    paramsline.value.pageSize = size;
    await handleSearchline(); // 数据刷新
};


//查询数据
onMounted(async () => {
    pageResult.value = await findrkd(params.value)
    console.log(pageResult.value)
    salesorder.value = pageResult.value.records
})


/**
 * 新增弹窗
 */
const insert = async () => {
    formdata.value = {
        recptCode: "",
        recptName: "",
        recptDate: "",
        poCode: "",
        supplierName: "",
        warehouseCode: "",
        warehouseNames: [],
        status: '0',
        totalAmount: "",
        remark: "",
        line: [],
    }; // 清空表单数据
    visible.value = true;
    activeName.value = false;
    title.value = "新增入库单";
    options.value = await findWarehousesList(); // 获取仓库列表
    console.log(options.value)

}


const updateID = () => {
    visible.value = true;
    activeName.value = true;
    title.value = "修改入库单";
}

/**
 * 修改弹窗
 */

const update = async (row) => {
    visible.value = true;
    activeName.value = true;
    title.value = "修改入库单";
    formdata.value = { ...row }; // 直接使用 row 的数据
    formdata.value.recptDate = new Date(formdata.value.recptDate); // 日期格式化
    options.value = await findWarehousesList(); // 重新获取仓库列表
    console.log(options.value)
    paramsline.value.recptCode = row.recptCode;
    pageResultline.value = await findline(paramsline.value)
    console.log(pageResultline.value)
    if (pageResultline.value.records.length > 0) {
        formdata.value.line = pageResultline.value.records[0].line;
        const a = [];
        a.push(formdata.value.warehouseId + '')
        a.push(formdata.value.warehouseAreaId + '')
        a.push(formdata.value.warehouseLocationCode)
        formdata.value.warehouseNames = a

    } else {
        formdata.value = []
    }




};


const rk = async (row) => {
    row.status = '1'
    await updaterkd(row)
    ElMessage.success('入库单已入库')
    handleSearch();
    console.log(row)
    row.line.forEach(item => {
        let a = reactive({})
        a.materialProductCode = item.materialProductCode
        a.materialProductName = item.productName
        a.specificationAndModel = item.specificationAndModel
        a.inventoryQuantity = item.quantityReceived
        a.unitId = item.unitId
        a.unitName = item.unitName
        a.inboundBatchNumber = item.batchCode
        a.warehouseCode = item.warehouseCode
        a.warehouseAreaCode = item.warehouseAreaCode
        a.warehouseLocationCode = item.warehouseLocationCode
        a.supplierCode = row.supplierCode
        a.supplierName = row.supplierName
        a.supplierAbbreviation = row.supplierAbbreviation
        a.productionOrder = row.workorderCode
        a.indate = new Date()
        a.validityPeriodOfInventory = new Date()
        // 添加接口调用
        insertStock(a)
    })
}


const customerSelect = async () => {
    const result = await findSupplier({ status: 0 });
    console.log(result);
    ghssalesorder.value = result.records;
    customerVisible.value = true;
    gystitle.value = "选择供应商";
    console.log(ghssalesorder.value)
}


const onSubmit = async () => {
    if (title.value == "新增入库单") {
        options.value.forEach(item => {
            console.log(item)
            if (item.value === formdata.value.warehouseNames[0]) {
                formdata.value.warehouseId = item.value + '';
                formdata.value.warehouseName = item.label;
            }
            item.children.forEach(it => {
                if (it.value === formdata.value.warehouseNames[1]) {
                    formdata.value.warehouseAreaName = it.label + "";
                    formdata.value.warehouseAreaId = it.value;
                }
                it.children.forEach(i => {
                    if (i.value === formdata.value.warehouseNames[2]) {
                        formdata.value.warehouseLocationCode = i.value + "";
                        formdata.value.warehouseLocationName = i.label;
                    }
                })
            })
        })
        console.log(formdata.value)
        await insertrkd(formdata.value)

    } else {
        ManeyNumber()
        console.log(formdata.value)
        await updaterkd(formdata.value)

    }
    visible.value = false
    ElMessage.success(`${title.value}成功`);

    await handleSearch();
}







const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.recptId) // 使用map方法过滤出选中行的logId数组

    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        formdata.value = { ...val[0] };//把选中的这条数据添加给修改数据（）
    }
}



//批量删除
const Delete1 = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleterkd(ids.value);  // 将单个ID传递给 deletesspplier 方法
        console.log(`删除的ID:`, ids.value);
        pageResult.value = await findrkd(params.value);
        salesorder.value = pageResult.value.records;
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};


//行内删除
const Delete2 = async (row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${row.recptId}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleterkd([row.recptId]);  // 将单个ID传递给 deletesspplier 方法

        console.log(`删除的ID:`, row.recptId);

        // 从表格数据中移除当前行
        salesorder.value = salesorder.value.filter(item => item.recptId !== row.recptId);

        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};



// 物料新增弹窗
const Wlinsert = () => {
    WlVisible.value = true;
    wltitle.value = "新增物料";
    wlformdata.value.warehouseNames = formdata.value.warehouseNames
}



// 物料修改弹窗
const Wlupdate = (row) => {
    WlVisible.value = true;
    wltitle.value = "修改物料";
    wlformdata.value = { ...row }; // 直接使用 row 的数据
    const a = [];
    a.push(wlformdata.value.warehouseId + '')
    a.push(wlformdata.value.warehouseAreaId + '')
    a.push(wlformdata.value.warehouseLocationCode)
    wlformdata.value.warehouseNames = a
    console.log(wlformdata.value, a)

}


// 物料新增/修改弹窗提交
const WlOnSubmit = async () => {
    if (wltitle.value == "新增物料") {
        console.log(wlformdata.value)
        options.value.forEach(item => {
            console.log(item)
            if (item.value === wlformdata.value.warehouseNames[0]) {
                wlformdata.value.warehouseId = item.value + '';
                wlformdata.value.warehouseName = item.label;
            }
            item.children.forEach(it => {
                if (it.value === wlformdata.value.warehouseNames[1]) {
                    wlformdata.value.warehouseAreaName = it.label + "";
                    wlformdata.value.warehouseAreaId = it.value;
                }
                it.children.forEach(i => {
                    if (i.value === wlformdata.value.warehouseNames[2]) {
                        wlformdata.value.warehouseLocationCode = i.value + "";
                        wlformdata.value.warehouseLocationName = i.label;
                    }
                })
            })
        })
        await insertline(wlformdata.value)
    } else {
        ManeyNumber()
        await updateline(wlformdata.value)

    }
    WlVisible.value = false
    ElMessage.success(`${wltitle.value}成功`);
    await handleSearchline();
}


function ManeyNumber() {
    let num = 0;
    formdata.value.line.forEach(item => {
        num = num + parseInt(item.wocumentAmount)
    })
    formdata.value.totalAmount = num;
}

const wlSelect = async () => {
    visibleBom.value = true;
    titlebom.value = "选择物料产品"
    const result = await findmaterialManagement();
    console.log(result);
    wlsalesorder.value = result.records;
    console.log(wlsalesorder.value)
}


// 行点击事件处理
const handleRowClick = (row) => {
    // 确保 formdata 是一个对象
    if (typeof formdata.value !== 'object' || formdata.value === null) {
        console.error('formdata is not an object:', formdata.value);
        return;
    }
    // 更新 formdata 中的 supplierName
    formdata.value.supplierName = row.supplierName;
    formdata.value.supplierCode = row.supplierCode;
    formdata.value.supplierId = row.supplierId;
    console.log('Selected supplier:', formdata.value.supplierName);
};

// 确定按钮点击事件处理
const onSubmitghs = () => {
    // 检查 formdata 是否有有效的供应商名称
    if (formdata.value.supplierName) {
        console.log('Form data submitted with supplier:', formdata.value);
        // 这里可以添加提交表单的逻辑
    } else {
        console.warn('No supplier selected');
    }

    // 关闭对话框
    customerVisible.value = false;
};









// 行点击事件处理
const handleRowClickwl = (row) => {
    console.log("--------------------", row);
    // 更新 
    wlformdata.value.recptId = formdata.value.recptId;
    wlformdata.value.materialNo = row.materialNo;
    wlformdata.value.specificationAndModel = row.specificationAndModel;
    wlformdata.value.materialProductCode = row.materialProductCode;
    wlformdata.value.productName = row.productName;
    wlformdata.value.unitName = row.unitId;
    wlformdata.value.unitName = row.unitName;

};


const handleSelectionChangebom = (val) => {
    idswl.value = val
    deleteDisabled.value = !val.length
    idswl.value = val.map(item => item.lineId) // 使用map方法过滤出选中行的logId数组
}

//批量删除bom
const Deletewl1 = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${idswl.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteline(idswl.value);
        console.log(`删除的ID:`, idswl.value);
        pageResultline.value = await findline(paramsline.value);
        console.log(pageResultline.value)
        idswl.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
        handleSearchline();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};


//单个删除bom
const Deletewl2 = async (row) => {
    try {
        // 弹出确认框
        await ElMessageBox.confirm(
            `是否确认删除访问编号为${row.lineId}的数据项？`,
            '系统提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 调用删除API
        await deleteline([row.lineId]);
        console.log(`删除的ID:`, row.lineId);

        // 重新获取最新的数据
        pageResultline.value = await findline(paramsline.value);
        console.log(pageResultline.value);

        // 如果需要，可以直接在这里处理页面更新逻辑
        // 例如：如果 `handleSearchline` 有其他功能（如重置分页），则可以保留
        handleSearchline();

        // 提示删除成功
        ElMessage({ type: 'success', message: '删除成功' });
    } catch (error) {
        if (error instanceof Error) {
            // 用户点击了取消按钮
            ElMessage({ type: 'info', message: '已取消删除' });
        } else {
            // 处理其他错误
            ElMessage({ type: 'error', message: '删除失败，请稍后再试' });
            console.error('删除失败:', error);
        }
    }
};



// 确定按钮点击事件处理
const onSubmit_wl = () => {

    // 关闭对话框
    visibleBom.value = false;

};

/**
 * 关闭弹窗,处理数据
 */
const handleClose = () => {
    resetData()
}

const handleClose_wl = () => {
    wlformdata.value = {}
    WlVisible.value = false;
    handleSearchline();
}
/**
 * 重置数据
 */
function resetData() {
    formdata.value = {}
    title.value = ''
}

let close = () => {
    visible.value = false;
    loadData();
};

let close_wl = () => {
    visibleBom.value = false;
};

let wlclose = () => {
    wlformdata.value = {}
    WlVisible.value = false;
};

let closegys = () => {
    customerVisible.value = false;
};



/**
 * 加载数据
 */
const loadData = async () => {
    await handleSearch();
};




/**
 * 重置搜索参数
 */
const paramsReset = () => {
    params.value = {
        currentPage: 1,
        pageSize: 5,
        recptCode: "",
        recptName: "",
        supplierName: "",
        recptDate: "",
        poCode: "",
    };
    paramsline.value = {
        currentPage: 1,
        pageSize: 5,
        recptCode: '',
    };
    handleSearch();

}
</script>

<style scoped>
.demo-pagination-block {
    display: flex;
    /* 使其成为 flexbox 容器 */
    justify-content: flex-end;
    /* 将内容对齐到右侧 */
    margin-top: 20px;
}
</style>
